package com.zhongen.common.core.util;

import lombok.experimental.UtilityClass;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

@UtilityClass
public class PinyinUtils {

	public String getPinyinFirstLetter(String chinese) {
		StringBuilder result = new StringBuilder();
		for (char c : chinese.toCharArray()) {
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
			if (pinyinArray != null && pinyinArray.length > 0) {
				result.append(pinyinArray[0].charAt(0));
			}
			else {
				result.append(c);
			}
		}
		return result.toString().toUpperCase();
	}

	public String getPinyinLetter(String chinese) {
		StringBuilder result = new StringBuilder();
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不显示声调
		for (char c : chinese.toCharArray()) {
			try {
				String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
				if (hanyuPinyinStringArray != null && hanyuPinyinStringArray.length > 0) {
					result.append(StringUtils.join(hanyuPinyinStringArray));
				}
				else {
					result.append(c);
				}
			}
			catch (BadHanyuPinyinOutputFormatCombination e) {
				throw new RuntimeException(e);
			}
		}
		return result.toString();
	}

}
